<?php

namespace app\common\behavior;


use app\common\model\CommissionLog;
use app\common\model\TaskItem;
use app\common\model\Tasks;
use app\common\model\TasksService;
use app\common\model\User;

class Task
{
    // 任务创建后
    public function taskCreateAfter(&$params)
    {
        $task = $params['task'];
        //到期关闭分钟数
        $task_auto_close_minue = get_addon_config('dep')['task_auto_close_minue'] ? get_addon_config('dep')['task_auto_close_minue'] : 15;
        // 更新任务，将过期时间存入订单，前台展示支付倒计时
        $task_ext = $task->ext_arr;
        $task_ext['expired_time'] = time() + ($task_auto_close_minue * 60); //当前到期时间

        \think\Queue::later(($task_auto_close_minue * 60), '\app\common\job\TaskAutoOper@autoClose', ['task' => $task,'action'=>'operCreate'], 'lingtu');

        // 更新订单扩展字段
        $task->ext = json_encode($task_ext);
        $task->save();

    }

    //任务完成后计入提成
    public function taskFinishAfter(&$params)
    {
        if (!$params['task']){
            return false;
        }
        //重新查询任务
        $task = Tasks::where('id', $params['task']['id'])->find();
        if (!$task){
            return false;
        }
        //取件人提成
        $this->pickCommission($task);
        //维修人提成计入
        $this->serviceCommission($task);
    }

    //计入取件人提成
    public function pickCommission($task)
    {
        //任务配件
        $taskItem = TaskItem::where('task_id',$task->id)->select();
        $money = 0;
        foreach ($taskItem as $item) {
            $money = bcadd($money,$item->total_fee,2);
        }
        //如果金额为 0 则不计入
        if (!$money){
            return false;
        }
        //计入取件提成
        CommissionLog::addLog($task,'pick',$task->pick_uid,$task->pick_nickname,$money);
    }


    //计入维修人提成
    public function serviceCommission($task)
    {
        //获取任务维修工艺
        $taskService = TasksService::where('task_id',$task->id)->select();
        //如果维修工艺不存在
        if (!count($taskService)){
            return false;
        }
        foreach ($taskService as $item) {
            //如果提成金额为空，跳出本轮循环
            if (!$item->total_fee){
                continue;
            }
            //查询该用户该订单的维修提成
            $commission = CommissionLog::getTaskService($item->task_id,$item->user_id);
            if (!$commission){
                //提成不存在，则添加
                if ($item->total_fee > 0){
                    CommissionLog::addLog($task,'service',$item->user_id,$item->user_nickname,$item->total_fee);
                }
            }else{
                //如果存在，则增加金额
                $commission->money = bcadd($commission->money,$item->total_fee,2);
                $commission->save();
            }
        }
    }


}
